import torch
import torch_mlu                      #添加的适配代码
import torch_mlu.utils.gpu_migration  #添加的适配代码
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
from datasets import load_dataset

# 检测是否有寒武纪 MLU 设备
device = "mlu:0" if torch.device("mlu") else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32

model_id = "/data/models/llm/models/whisper-large-v3"

# 加载模型到 MLU
model = AutoModelForSpeechSeq2Seq.from_pretrained(
    model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
)
model.to(device)

processor = AutoProcessor.from_pretrained(model_id)

pipe = pipeline(
    "automatic-speech-recognition",
    model=model,
    tokenizer=processor.tokenizer,
    feature_extractor=processor.feature_extractor,
    torch_dtype=torch_dtype,
    device=device,  # 这里可以直接传 "mlu:0"
)

# 数据集（英语语音样例）
dataset = load_dataset("distil-whisper/librispeech_long", "clean", split="validation")
sample = dataset[0]["audio"]

result = pipe(sample, return_timestamps=True)
print(result["text"])

#result = pipe(sample)
#print(result["text"])
